﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using Xiaov.SmartWeb.Model;

namespace Xiaov.SmartWeb.Application.TZGC
{
  public partial class XM : BasePage
  {
    private string _moduleid;
    public string ModuleID
    {
      get
      {
        if (Request.QueryString["mid"] != null)
        {
          _moduleid = Request.QueryString["mid"].ToString();
        }
        else
        {
          _moduleid = "0000";
        }
        return _moduleid;
      }
    }

    //权限检查
    protected void Page_Init(object sender, EventArgs e)
    {
        PM_Filter();
    }

    //页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        //形成树
        TreeView1.Nodes.Clear();
        IniTree(TreeView1.Nodes, "0");        
        //隐藏树
        TreeView1.Visible = false;
        //绑定grid
        BindGrid();
      }
    }

    #region 递归形成树形菜单的函数
    //建树的基本思路是：从根节点开始递归调用显示子树 
    private void IniTree(TreeNodeCollection Nds, string parentId)
    {
      //形成树形菜单用的DataTable、DataSet
      DataTable treedt;
      DataSet treeds;

      treedt = new DataTable();
      treeds = new DataSet();

      //查询节点的SQL
      string treesql = @"select * from yt_xmlbb ";


      treeds = Maticsoft.DBUtility.DbHelperOra.Query(treesql);
      treedt = treeds.Tables[0];

      DataView treedv = new DataView();
      TreeNode tmpNd;
      string intId;
      treedv.Table = treeds.Tables[0];
      treedv.RowFilter = "FLBBM='" + parentId + "'";
      foreach (DataRowView drv in treedv)
      {
        tmpNd = new TreeNode();
        tmpNd.Value = drv["LBBM"].ToString();
        //tmpNd.Tag = drv["PID"].ToString();
        tmpNd.Text = drv["LBMC"].ToString();
        Nds.Add(tmpNd);
        intId = drv["FLBBM"].ToString();
        //InitTree(tmpNd.Nodes, tmpNd.Tag.ToString());
        IniTree(tmpNd.ChildNodes, tmpNd.Value);
      }
    }


    #endregion

    //绑定GRID
    protected void BindGrid()
    {
      StringBuilder sql_query = new StringBuilder();
      sql_query.Append(" select c.*,decode(wczt,0,'未完成','已完成') as zt,c.rowid  from yt_xmb c where 1=1 ");
      
      
      if (!string.IsNullOrEmpty(TextBox1.Text.ToString().Trim()))
      {
          sql_query.Append(" and c.xmmc like '%" + TextBox1.Text.ToString().Trim() + "%'  ");
      }

      if (DropDownList1.SelectedValue != "-1")
      {
          sql_query.Append(" and c.wczt = '" + DropDownList1.SelectedValue.ToString() + "'  ");
      }

      sql_query.Append(" order by c.xmmc ");

      GridView1.DataSource = Maticsoft.DBUtility.DbHelperOra.Query(sql_query.ToString());
      GridView1.DataBind();
    }

    //页面翻页
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
      GridView1.PageIndex = e.NewPageIndex;//分页BindData();
      BindGrid();
    }

    //操作事件 编辑/改变状态/删除
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ClearTextbox();
        hfXMID.Value = e.CommandArgument.ToString();
        switch (e.CommandName)
        {
            case "bianji":
            string xmbm_bianji;
            xmbm_bianji = e.CommandArgument.ToString();

            StringBuilder sql_query = new StringBuilder();
            sql_query.Append("select *  ");
            sql_query.Append(" from yt_xmb c ");
            sql_query.Append(" where xmid = '" + xmbm_bianji + "' ");

            OracleDataReader mydr;
            mydr = (OracleDataReader)Maticsoft.DBUtility.DbHelperOra.ExecuteReader(sql_query.ToString());

              while (mydr.Read())
              {
                txtxmbm.Text = mydr["xmbm"].ToString();
                txtxmmc.Text = mydr["xmmc"].ToString();            
                txtlbbm.Text = mydr["sslbbm"].ToString();
                txtsspxbm.Text = mydr["sspxbm"].ToString();
                txtJZGCBL.Text = mydr["JZGCBL"].ToString();
                txtAZGCBL.Text = mydr["AZGCBL"].ToString();
                txtSBGZBL.Text = mydr["SBGZBL"].ToString();
                txtQTBL.Text = mydr["QTBL"].ToString();
                cbSFWC.Checked = mydr["wczt"].ToString() == "0" ? false : true;
          }
          mydr.Close();
          txtlb.Text = GetXMLBMC(txtsspxbm.Text.ToString().Trim());         
          btn_save.Text = "保存";         
          break;
        case "guishu":
          string xmbm_guishu;
          xmbm_guishu = e.CommandArgument.ToString();
          /*  Rectangle ScreenArea = System.Windows.Forms.Screen.GetWorkingArea(this);
            int width1 = ScreenArea.Width; //屏幕宽度 
            int height1 = ScreenArea.Height; //屏幕高度*/

          string js = "window.open('GCGuiShu.aspx?xmid=" + xmbm_guishu + "','','left=150,top=100,width=1000,height=650,toolbar=no,resizable=yes,location=no')";
          Response.Write("<script type='text/javascript' language='javascript'>" + js + "</script>");
          break;
        case "shanchu":
          string sql_del;
          string xmbm_shanchu;  //实际是所属项目ID
          xmbm_shanchu = e.CommandArgument.ToString(); 

          //如果该项目下有工程，则不能删除该项目
          string sql_count;
          sql_count = "select count(*) from yt_gcb where ssxmbm = '" + xmbm_shanchu + "'";
          object oo = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_count);
          int count_gc;
          if (oo != null)
          {
            count_gc = Convert.ToInt32(oo);
          }
          else
          {
            count_gc = 0;
          }

          if (count_gc == 0)
          {            
            //删除项目表中的记录
            sql_del = "delete from yt_xmb where xmid =  '" + xmbm_shanchu + "'";
            Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_del);
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('删除成功！')</script>");
            BindGrid();
          }
          else
          {
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('该项目下仍有工程，请到工程管理页面移走所属工程！')</script>");
          }

          break;

        default:
          btn_save.Text = "增加";
          break;
      }
    }

    //得到项目类别的详细名称
    protected string GetXMLBMC(string pxbm)
    {
        string lbmc_wanzheng;   //完整的类别名称       
        string sql2;
        sql2 = @"select replace(a.lbmc || '-' || b.lbmc || '-' || c.lbmc || '-' || d.lbmc || '-' ||
                 e.lbmc || '-' || f.lbmc || '-' || g.lbmc || '-' || h.lbmc,
                 '-' || i.lbmc,'') || '-' || i.lbmc
                 from (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 2)) a,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 4)) b,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 6)) c,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 8)) d,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 10)) e,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 12)) f,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 16)) g,
                 (select lbmc from yt_xmlbb where pxbm = substr('{0}', 1, 18)) h,
                 (select lbmc from yt_xmlbb where pxbm = '{0}') i";
        sql2 = string.Format(sql2, pxbm);
        lbmc_wanzheng = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql2).ToString();
        return lbmc_wanzheng;
    }

    //隔行换色
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        //鼠标移动到某行上，该行变色
        e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#dddddd'");
        //鼠标移开后，恢复
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        //序号
        e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
        //在grid中显示详细的类别名称
        string a = GridView1.DataKeys[e.Row.RowIndex].Values["SSPXBM"].ToString();
        e.Row.Cells[3].Text = GetXMLBMC(GridView1.DataKeys[e.Row.RowIndex].Values["SSPXBM"].ToString());        
      }
    }

    protected bool CheckBLSum()
    {
        bool bl_sum;
         decimal JZGCBL, AZGCBL, SBGZBL, QTBL,sumbl;
        JZGCBL = txtJZGCBL.Text.ToString().Trim() == "" ? 0 : Convert.ToDecimal(txtJZGCBL.Text.ToString().Trim());
          AZGCBL = txtAZGCBL.Text.ToString().Trim() == "" ? 0 : Convert.ToDecimal(txtAZGCBL.Text.ToString().Trim());
          SBGZBL = txtSBGZBL.Text.ToString().Trim() == "" ? 0 : Convert.ToDecimal(txtSBGZBL.Text.ToString().Trim());
          QTBL = txtQTBL.Text.ToString().Trim() == "" ? 0 : Convert.ToDecimal(txtQTBL.Text.ToString().Trim());
          sumbl = JZGCBL + AZGCBL + SBGZBL + QTBL;
          if (sumbl == 0 || sumbl == 100)
          {
              bl_sum = true;
          }
          else
          {
              bl_sum = false;
          }
          return bl_sum;

    }
    //保存
    protected void btn_save_Click(object sender, EventArgs e)
    {
      if (CheckBLSum())
      {
          if (String.IsNullOrEmpty(hfXMID.Value.ToString()))  //新增
          {
              string xmbm, xmmc, sslbbm, sspxbmbm;
              string JZGCBL, AZGCBL, SBGZBL, QTBL;
              xmmc = txtxmmc.Text.ToString().Trim();          
              sslbbm = txtlbbm.Text.ToString().Trim();
              sspxbmbm = txtsspxbm.Text.ToString().Trim();
              xmbm = sspxbmbm + "_" + xmmc;
              JZGCBL = txtJZGCBL.Text.ToString().Trim() == "" ? "null" : txtJZGCBL.Text.ToString().Trim();
              AZGCBL = txtAZGCBL.Text.ToString().Trim() == "" ? "null" : txtAZGCBL.Text.ToString().Trim();
              SBGZBL = txtSBGZBL.Text.ToString().Trim() == "" ? "null" : txtSBGZBL.Text.ToString().Trim();
              QTBL = txtQTBL.Text.ToString().Trim() == "" ? "null" : txtQTBL.Text.ToString().Trim();

              //判断是否有重复的记录-项目表
              string  sql_query;
              int  flag_xm;          

              sql_query = "select count(*) from yt_xmb where xmbm = '" + xmbm + "' ";
              flag_xm = Convert.ToInt32(Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_query));
              if (flag_xm == 0)
              {
                  sql_query = "select decode(max(to_number(xmid)),null,1,max(to_number(xmid))+1) from yt_xmb";
                  string xmid = Convert.ToString(Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_query));
                  string sql_insert;
                  string sfwc = cbSFWC.Checked ? "1" : "0";
                  sql_insert = @"insert into yt_xmb (xmid,xmbm,XMMC,SSLBBM,SSPXBM,JZGCBL, AZGCBL, SBGZBL, QTBL,wczt) 
                                    values ('" + xmid + "','" + xmbm + "','" + xmmc + "','" + sslbbm + "','" + sspxbmbm + "',"
                                                 + JZGCBL + "," + AZGCBL + "," + SBGZBL + "," + QTBL + "," + sfwc + ")";
                  Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_insert);
                  this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('保存成功！')</script>");
                  BindGrid();
                  ClearTextbox();
              }
              else
              {
                  this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('该项目已存在，请检查！')</script>");         
              }   
        }
        else   //更新
        {
              string xmndrowid, xmrowid, xmbm, xmmc, nd, sslbbm, sspxbmbm;
              string JZGCBL, AZGCBL, SBGZBL, QTBL;
              xmndrowid = txtxmndrowid.Text.ToString().Trim();
              xmrowid = txtxmrowid.Text.ToString().Trim();
              xmmc = txtxmmc.Text.ToString().Trim();
              sslbbm = txtlbbm.Text.ToString().Trim();
              sspxbmbm = txtsspxbm.Text.ToString().Trim();
              xmbm = sspxbmbm + "_" + xmmc;
              JZGCBL = txtJZGCBL.Text.ToString().Trim() == "" ? "null" : txtJZGCBL.Text.ToString().Trim();
              AZGCBL = txtAZGCBL.Text.ToString().Trim() == "" ? "null" : txtAZGCBL.Text.ToString().Trim();
              SBGZBL = txtSBGZBL.Text.ToString().Trim() == "" ? "null" : txtSBGZBL.Text.ToString().Trim();
              QTBL = txtQTBL.Text.ToString().Trim() == "" ? "null" : txtQTBL.Text.ToString().Trim();

              //更新项目表
              string sql_update_xm;
              string sfwc = cbSFWC.Checked ? "1" : "0";
              sql_update_xm = @"update yt_xmb set xmbm='" + xmbm + "',XMMC = '" + xmmc + "',SSLBBM = '" + sslbbm
                + "',SSPXBM = '" + sspxbmbm + "',JZGCBL = " + JZGCBL + ",AZGCBL = " + AZGCBL + ",SBGZBL = "
                + SBGZBL + ",QTBL = " + QTBL + ",wczt='" + sfwc + "'  where xmID = '" + hfXMID.Value + "'";
              Maticsoft.DBUtility.DbHelperOra.ExecuteSql(sql_update_xm);

              BindGrid();
              this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('保存成功！')</script>");
              ClearTextbox();
         }
      }
      else
      {
          this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示", "<Script Language='JavaScript'>window.alert('输入的比例不合法！')</script>");          
      }
     
    }

    //取消
    protected void Button1_Click(object sender, EventArgs e)
    {
      ClearTextbox();
    }

    private void ClearTextbox()
    {
        hfXMID.Value = null;
        txtxmbm.Text = "";
        txtxmmc.Text = "";      
        txtlbbm.Text = "";
        txtlb.Text = "";
        txtsspxbm.Text = "";
        txtxmndrowid.Text = "";
        txtxmrowid.Text = "";
        txtJZGCBL.Text = "";
        txtAZGCBL.Text = "";
        txtSBGZBL.Text = "";
        txtQTBL.Text = "";
        cbSFWC.Checked = false;
        btn_save.Text = "增加";
    }


    //选择项目类别
    protected void Button5_Click(object sender, EventArgs e)
    {
      if (TreeView1.Visible == false)
      {
        TreeView1.Visible = true;
        Button5.Text = "取消";
      }
      else
      {
        TreeView1.Visible = false;
        Button5.Text = "选择";
      }
    }


    //在树上选择节点，将选中的节点内容放入文本框中，并隐藏树
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
      //绑定所选节点信息
      string lbbm = TreeView1.SelectedNode.Value;
      string lbmc, sspxbm;
      lbmc = null;

      int flag = 1;
      string sql_query;
      sql_query = "select count(*) from yt_xmlbb where flbbm = '" + lbbm + "' ";
      flag = Convert.ToInt32(Maticsoft.DBUtility.DbHelperOra.GetSingle(sql_query));
      if (flag == 0)
      {
        string sql1, sql2;
        sql1 = "select lbmc from yt_xmlbb where lbbm = '" + lbbm + "'";
        sql2 = "select pxbm from yt_xmlbb where lbbm = '" + lbbm + "'";
        lbmc = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql1).ToString();
        sspxbm = Maticsoft.DBUtility.DbHelperOra.GetSingle(sql2).ToString();

        //实际用的
        txtlbbm.Text = lbbm;        
        txtsspxbm.Text = sspxbm;
        txtlb.Text = GetXMLBMC(sspxbm);
        TreeView1.Visible = false;
        Button5.Text = "选择";
      }
      else
      {
        Response.Write("<script>alert('必须选择最末级类别!')</script>");
      }
      //消除节点的选中状态
      TreeView1.SelectedNode.Selected = false;
    }


    //选择年份
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
      BindGrid();
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
      BindGrid();
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        GridView1.Columns[1].Visible = false;        
        GridView1.Columns[10].Visible = false;
        GridView1.Columns[11].Visible = false;
        GridView1.Columns[12].Visible = false;
    }

    //查询按钮
    protected void Button6_Click(object sender, EventArgs e)
    {
      BindGrid();
    }


  }
}